package com.myapp.handler;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myapp.Logical.interfaces.ILogical;
import com.myapp.msg.base.BaseMsg;
import com.myapp.user.Role;
import com.myapp.user.Status;
import com.myapp.user.UserBean;
import com.myapp.data.global.Instances;

/**
 * Servlet implementation class Handler
 */
@WebServlet(name = "hdr", description = "消息入口", urlPatterns = { "/hr", "/hr1" }, asyncSupported = true)
public class Handler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Handler() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO 取用户id
		String uid = request.getSession().getId();

		// 初始化用户bean
		UserBean userBean = Instances.getUserContianer().getUserBeanById(uid);

		// 消息
		BaseMsg msg = (BaseMsg) request.getAttribute("msg");

		// 业务
		ILogical logical = (ILogical) request.getAttribute("logical");
		if (msg == null || logical == null) {// 消息为空或者业务为空
			return;
		}

		boolean legal = false;
		switch (msg.getMsgConfigBean().getPermission()) {
		case UNAUTHORIZE: {
			legal = true;
			break;
		}
		case AUTHORIZE: {
			if (userBean.getStatus() == Status.AUTHORIZE) {
				legal = true;
			}
			break;
		}
		case GM: {
			if (userBean.getStatus() == Status.AUTHORIZE
					&& userBean.getRole() == Role.GM) {
				legal = true;
			}
			break;
		}
		}

		// 如果合法就转发
		if (legal) {
			// 启动异步线程，不阻塞主线程
			// AsyncContext ctx = request.startAsync(request, response);
			// 执行业务流程
			List<BaseMsg> msgs = logical.doLogical(userBean, msg);

			// 有需要返回的消息时，调用编码器进行数据整理
			if (msgs != null && msgs.size() > 0) {
				// 消息编码
				ByteBuffer byteBuffer = Encoder.encode(msgs);
				int length = byteBuffer.limit();
				// 设置内容长度
				// ServletResponse repsonse_sync = ctx.getResponse();
				response.setContentLength(length);

				// 发送数据
				OutputStream os = response.getOutputStream();
				os.write(byteBuffer.array());
				os.flush();

				// 关闭输出流
				os.close();
			}
			// 分步
			// ctx.complete();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
